using UnityEngine;
using System.Collections;

public class Projectile : MonoBehaviour 
{
	//For effects when flying through the space.
	public ParticleEmitter smokeyTrail;
	
	//Sound. This will be the holder for the basic musical notes i.e Do Re Me etc.
	public AudioClip fireSound;
	public AudioClip destroyedSound;
	
	public float damage = 10.0F;
	public float power;
	private Vector3 direction;
	private bool isFired;
	private SpriteManager spriteManager = GameObject.Find ( "SpriteManager" ).GetComponent<SpriteManager>();
	private GameObject target;
	
	// Use this for initialization
	void Start () 
	{
		this.gameObject.AddComponent<AudioSource>();
		this.gameObject.AddComponent<SphereCollider>();
		this.gameObject.GetComponent<SphereCollider>().radius = 1.0F;
		target = null;		
		direction  = new Vector3 ( 0, 1, 0 );
		isFired = false;
		
	}
	
	// Update is called once per frame
	void Update ( )
	{
		if ( target )
		{
			if ( isFired )
			{
				//Update location and orientation of the mob
				setProjectileDir ( ( target.transform.position - this.transform.position ).normalized );
				this.transform.position = this.transform.position + direction * power;
			}
		}
	}
	
	public void setDamage ( float dmg )
	{
		damage = dmg;	
	}
	
	public float getDamage ( )
	{
		return damage;	
	}
	
	public void setCollisionRange ( float rge )
	{
		this.gameObject.AddComponent<SphereCollider>().radius = rge;
	}
	
	public float getCollisionRange ()
	{
		return this.gameObject.GetComponent<SphereCollider>().radius;
	}
	
	void OnCollisionEnter ( Collision hit )
	{
		if ( hit.gameObject.tag == "enemy" )
		{
			//Access hit object's script to modify it's health.
			if ( destroyedSound )
				this.gameObject.GetComponent<AudioSource>().PlayOneShot(destroyedSound);
			Destroy ( this.gameObject );
		}
	}
	
	public void setTarget ( GameObject tgt )
	{		
		target = tgt;	
	}
	
	public GameObject getTarget ()
	{
		return target;
	}

	public void setProjectileDir ( Vector3 dir )
	{
		direction = dir;	
	}
	
	public Vector3 getProjectileDir ( )
	{
		return direction;
	}
	
	public void setProjectilePower ( float powa )
	{
		power = powa;
	}
	
	public float getProjectilePower ( )
	{
		return power;
	}
	
	public void fire ( )
	{
		if ( target )
		{
			//if ( fireSound )
				//this.gameObject.GetComponent<AudioSource>().PlayOneShot ( fireSound );
			
			this.transform.LookAt ( target.transform );
			isFired = true;
			setProjectileDir ( ( target.transform.position - this.transform.position ).normalized );
			//Turn on smokey trail animation or use particle system attached to this projectile.
		}
		else
			Debug.Log ( "WARNING! NO TARGET SET TO THIS PROJECTILE!" );
	}
	
}
